package cn.chongho.inf.flink.restapi;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * 第三方系统登录。
 * @author ming
 */

@Service
@Slf4j
public class LoginApi {

    @Value("${sys.login.url}")
    private String loginUrl;

    @Autowired
    private RestTemplate restTemplate;

    public JSONObject getUser(String account, String password){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("account", account);
        jsonObject.put("password", password);
        jsonObject.put("loginType", "password");
        HttpHeaders headers = new HttpHeaders();
        //定义请求参数类型，这里用json所以是MediaType.APPLICATION_JSON
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> formEntity = new HttpEntity<>(jsonObject.toJSONString(), headers);
        JSONObject userJsonObject = restTemplate.postForObject(loginUrl + "/oauth/token", formEntity, JSONObject.class);
        if(userJsonObject.getBoolean("success")){
            return userJsonObject.getJSONObject("data");
        }
        return null;
    }
}
